package de.upb.messerschmidt.set;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import de.upb.messerschmidt.set.entity.Message;
import de.upb.messerschmidt.set.jdo.PMF;

/**
 * This Servlet returns a user's messages.
 * 
 * @author Tim Messerschmidt
 * 
 */
public class GetMessageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@SuppressWarnings("unchecked")
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String user = req.getParameter("user");

		if (user != null) {
			PersistenceManager pm = PMF.get().getPersistenceManager();
			// Query the PersistenceManager for Messages
			Query query = pm.newQuery(Message.class);
			query.setFilter("target == targetParam");
			query.declareParameters("String targetParam");
			query.setOrdering("date desc");
			try {
				List<Message> results = (List<Message>) query.execute(user);
				if (!results.isEmpty()) {
					Gson gson = new Gson();
					String json = gson.toJson(results);
					resp.setStatus(200);
					resp.getWriter().println(URLEncoder.encode(json, "UTF-8"));
				} else {
					resp.setStatus(200);
					resp.getWriter().println("no messages");
				}
			} finally {
				query.closeAll();
			}
		} else {
			resp.setStatus(200);
			resp.getWriter().println("no user defined");
		}
	}

}
